package com.sun.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.pojo.Tag;
import com.sun.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author: glorysun
 * @date: 2020/8/5
 */
@Controller
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private TagService tagService;

    //标签列表页
    @GetMapping("/tags")
    public String list(Model model, @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum, 5);
        List<Tag> tagList = tagService.selectTagList();
        //得到分页结果对象
        PageInfo<Tag> pageInfo = new PageInfo<>(tagList);
        model.addAttribute("pageInfo", pageInfo);
        return "admin/tags";
    }

    //标签新增页
    @GetMapping("/tags/input")
    public String toInput(){
        return "admin/tags-input";
    }

    //保存新增
    @GetMapping("/tags/inputSave")
    public String input(Tag tag, RedirectAttributes attributes){
        Tag tag1=tagService.selectTagByName(tag.getName());
        System.out.println(tag1);
        if(tag1==null){
            int i=tagService.insertTag(tag);
            if(i>0)
                attributes.addFlashAttribute("message","添加成功!");
            else
                attributes.addFlashAttribute("message","添加失败!");
            return "redirect:/admin/tags";
        }else {
            attributes.addFlashAttribute("message","标签已存在!");
            return "redirect:/admin/tags/input";
        }
    }

    //标签更新页
    @GetMapping("/tags/edit/{id}")
    public String toEdit(@PathVariable Long id, HttpSession session){
        Tag tag=tagService.selectTagById(id);
        session.setAttribute("tag",tag);
        return "admin/tags-edit";
    }

    //保存更新
    @GetMapping("/tags/editSave")
    public String edit(Tag tag,RedirectAttributes attributes,HttpSession session){
        Tag tag1=tagService.selectTagByName(tag.getName());
        if(tag1==null){
            attributes.addFlashAttribute("message","更新成功!");
            session.removeAttribute("tag");
            tagService.updateTag(tag);
            return "redirect:/admin/tags";
        }else {
            session.setAttribute("message","标签已存在!");
            return "admin/tags-edit";
        }
    }

    //删除标签
    @GetMapping("/tags/delete/{id}")
    public String delete(@PathVariable Long id,RedirectAttributes attributes){
        attributes.addFlashAttribute("message","删除成功");
        tagService.deleteTag(id);
        return "redirect:/admin/tags";
    }
}
